package com.realphim.app.indie.videoplayer;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;

import com.realphim.app.R;
import com.realphim.app.indie.entities.Video;

public class VideoLoaderActivity extends Activity {

    public final static String PARAM_VIDEO_ID = "video_id";

    private int videoId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_loader);

        videoId = getIntent().getExtras().getInt("id");

        doLoadVideo(videoId);
    }

    private void doLoadVideo(int videoId) {
        String url = "http://realphim.com/api/film/get_film?id=" + videoId;
        LoadJsonVideoTask loadJsonTask = new LoadJsonVideoTask();
        loadJsonTask.execute(url);
    }

    class LoadJsonVideoTask extends AsyncTask<String, Void, Void> {

        Video video = null;

        ArrayList<Video> episodes = null;

        protected Void doInBackground(String... urls) {
            JSONObject json = null;
            String str = "";
            HttpResponse response;
            HttpClient myClient = new DefaultHttpClient();
            HttpGet myConnection = new HttpGet(urls[0]);

            try {
                response = myClient.execute(myConnection);
                str = EntityUtils.toString(response.getEntity(), "UTF-8");
                json = new JSONObject(str);

                // Load video
                video = loadVideoFromJson(json);
                int vNumEpisodes = json.getInt("last_episode");
                JSONArray jsonEpisodeList = json.getJSONArray("episode_list");

                if (vNumEpisodes > 1) {
                    episodes = new ArrayList<Video>(vNumEpisodes);

                    for (int i = 0; i < jsonEpisodeList.length(); i++) {
                        JSONObject jsonEpisode = jsonEpisodeList
                                .getJSONObject(i);
                        Video episode = loadVideoFromJson(jsonEpisode);
                        episode.setEpisodeId(episode.getId());
                        // Default episode name if empty
                        if (TextUtils.isEmpty(episode.getTitle())) {
                            episode.setEpisodeTitle("Tâp " + (i + 1));
                        } else {
                            episode.setEpisodeTitle(episode.getTitle());
                        }
                        episode.setId(video.getId());
                        episode.setTitle(video.getTitle());

                        episodes.add(episode);
                    }
                }

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(Void param) {
            Intent intent = new Intent(VideoLoaderActivity.this,
                    VideoPlayerActivity.class);
            intent.putExtra(VideoPlayerActivity.PARAM_VIDEO, video);
            intent.putExtra(VideoPlayerActivity.PARAM_EPISODES, episodes);
            VideoLoaderActivity.this.startActivity(intent);
            VideoLoaderActivity.this.finish();
        }

        private Video loadVideoFromJson(JSONObject json) throws JSONException {
            String vId = json.getString("id");
            String vTitle = json.getString("title");
            String vUrl360 = json.getString("file_360");
            String vUrl480 = json.getString("file_480");
            String vUrl640 = json.getString("file_640");
            String vUrlMHD = json.getString("file_mhd");
            String vUrl720 = json.getString("file_720");
            String vUrl1080 = json.getString("file_1080");
            String vSubVn = json.getString("sub_vn");
            String vSubEn = json.getString("sub_en");
            String vSubOther = json.getString("sub_other");

            Video video = new Video(vId, vTitle, vUrl360, vUrl480, vUrl640,
                    vUrlMHD, vUrl720, vUrl1080, vSubVn, vSubEn, vSubOther);

            return video;
        }
    }

}
